package codepulse.blogmoon.cn.common.dubbo;

import codepulse.blogmoon.cn.common.context.Context;
import codepulse.blogmoon.cn.common.exception.BizException;
import codepulse.blogmoon.cn.common.utils.GsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.Filter;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcContext;
import org.apache.dubbo.rpc.RpcException;

/**
 * 消费者上下文
 */

@Slf4j
@Activate(group = {CommonConstants.CONSUMER},order = -27000)
public class DubboConsumerContextFilter  implements Filter,Filter.Listener{
    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        try {
            RpcContext.getServiceContext().setAttachment("context", GsonUtil.toJson(Context.get()));
            Result result = invoker.invoke(invocation);
            return result;
        } catch (BizException e) {
            throw e;
        }
    }

    @Override
    public void onResponse(Result appResponse, Invoker<?> invoker, Invocation invocation) {

    }

    @Override
    public void onError(Throwable t, Invoker<?> invoker, Invocation invocation) {

    }
}
